
package tech.wisefin.track;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Component
public class TrackFilter extends HttpFilter {

    private final TrackConfiguration config;

    public TrackFilter(TrackConfiguration config) {
        this.config = config;
    }

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO: 当进入到不同的页面，时需要返回不同的编号
        // 这个编号是需要和人、时间、业务进行绑定，并且不能被伪造
        //
        // 并且在多个系统之间的页面是可以使用同一个编号，用于跨系统的追踪
        String trackId = request.getHeader(config.getTraceName());
        if (trackId == null) {
            trackId = UUID.randomUUID().toString();
        }

        // XXX: 如果是服务器端生成页面，可以直接写入 Cookie
        response.addHeader(config.getTraceName(), trackId);
        super.doFilter(request, response, chain);
    }
}
